//
//  AccountDetailViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/11/21.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "AccountDetailViewController.h"
#import "PagingData.h"
#import "GetPagingDataList.h"

@interface AccountDetailViewController ()<UITableViewDataSource,UITableViewDelegate,PagingDataListServiceDelegate>{
    
    __weak IBOutlet UITableView *_tableView;
    GetPagingDataList *DataService;
}

@end

@implementation AccountDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithNavTitle:(NSString *)NavTitle type:(NSString *)type{
    self = [super init];
    if (self) {
        _navTitle = NavTitle;
        _type = type;
        //获取数据
        [self getDate];
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    // 集成刷新控件
    [self setupRefresh];
    [_tableView headerBeginRefreshing];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setUI];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.rowHeight = 55;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  设置UI
 */
-(void)setUI{
    self.navigationItem.title = _navTitle;
    //返回
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
}

#pragma mark - CustomMethod
-(void)back{
    DataService = nil;
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark UITableView Method

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (DataService.pageInfo.dataArr.count != 0) {
        return DataService.pageInfo.dataArr.count;
    }else{
        return 0;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"cellId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"AccountRecordCell" owner:nil options:nil][0];
    }
    NSInteger row = indexPath.row;
    UILabel *describe = (UILabel *)[cell.contentView viewWithTag:2];
    UILabel *money = (UILabel *)[cell.contentView viewWithTag:3];
    UILabel *time = (UILabel *)[cell.contentView viewWithTag:4];
    describe.text = DataService.pageInfo.dataArr[row][@"remark"];
    money.text = [NSString stringWithFormat:@"%@元",DataService.pageInfo.dataArr[row][@"jifen"]];
    time.text = DataService.pageInfo.dataArr[row][@"time"];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//获取数据
-(void)getDate{
    DataService = [[GetPagingDataList alloc]initWithAction:@"jifenjilulist" Type:_type];
    DataService.delegate = self;
    
}
#pragma mark 刷新

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 刷新表格
    if (DataService.isQuery ||![Constants isExistenceNetwork]) {
        [_tableView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView headerEndRefreshing];
        return;
    }
    
    // 下拉刷新 （请求第一页数据）
    
    // 每次必须重置下 否则会数据混乱
    DataService.pageInfo.pageno = @"1";
    [DataService pageQuery];
}

- (void)footerRereshing
{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView footerEndRefreshing];
        
        return;
    }
    
    // 如果正在查询 或 没有更多数据了
    //    NSLog(@"%i",linkService.isQuery);
    //    NSLog(@"%i",linkService.pageInfo.hasMoreData);
    if (DataService.isQuery || !DataService.pageInfo.hasMoreData) {
        // 2. 1秒后刷新表格UI
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [_tableView footerEndRefreshing];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"没有更多数据了";
            [hud hide:YES afterDelay:1];
        });
        
        DataService.pageInfo.hasMoreData = YES;
        
        return;
    }
    
    // 如果还有更多数据 请求下一页
    [DataService.pageInfo nextPage];
    [DataService pageQuery];
}
#pragma mark - QuestionService Delegate

- (void)didRecieveData{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}
- (void)didRecieveMsg{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}


@end
